package com.woniu.liuzhougov.authorityControl.realm;

import com.woniu.liuzhougov.authorityControl.constant.UserConstant;
import com.woniu.liuzhougov.authorityControl.pojo.User;
import com.woniu.liuzhougov.authorityControl.service.RightsService;
import com.woniu.liuzhougov.authorityControl.service.RoleService;
import com.woniu.liuzhougov.authorityControl.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @version 1.0
 * @Author zhuxinpan
 * @ClassName UserRealm
 * @Description 配置realm
 * @Date 2019/4/19 15:25
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Resource
    private RightsService rightsService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        Set<String> perms = new HashSet<>(rightsService.listPermsByUserId(user.getUserId()));
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }

    /**
     * @return org.apache.shiro.authc.AuthenticationInfo
     * @Author zhuxinpan
     * @Description 登录验证功能
     * @date 2019/4/19 15:28
     * @params [authenticationToken]
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userLoginName = (String) authenticationToken.getPrincipal();
        User userInDataSource = userService.getUserByLoginName(userLoginName);
        if (userInDataSource == null) {
            throw new UnknownAccountException("没有这个账户");
        }
        if (userInDataSource.getUserStatus() != null && userInDataSource.getUserStatus().getUserStatusId() != UserConstant.USER_STATUS_NORMAL) {
            throw new LockedAccountException("账号已锁定!请联系管理员!");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInDataSource, userInDataSource.getUserPass(), getName());
        return info;
    }

    /**
     * @return void
     * @Author zhuxinpan
     * @Description 测试代码 生成用户密码
     * @date 2019/4/18 19:53
     * @params [args]
     */

    /*public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123", null, 3);
        System.out.println(md5Hash);
    }*/

}
